<?php

namespace Xlib\Form\Element;

use Zend\Form\Element\Password as ZendPassword;
use Zend\Form\View\Helper\FormPassword as PasswordHelper;
use Zend\Form\View\Helper\FormLabel as LabelHelper;
use Xlib\Form\ElementInterface;

class Password extends ZendPassword implements ElementInterface {

    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);
        $attributes = null;
        $labelAttributes = null;
        if (isset($options['attributes'])) {
            $attributes = (array) $options['attributes'];
        }
        if (isset($options['labelAttributes'])) {
            $labelAttributes = (array) $options['labelAttributes'];
        }
        $this->prepareAttributes($attributes);
        $this->prepareLabelAttributes($labelAttributes);
    }

    protected function prepareAttributes(array $elementAttributes = null)
    {
        // TODO: использовать обработку дополнительных классов !!!
        $elementAttributes = (array) $elementAttributes;
        $elementName       = $this->getName();
        $elementClasses    = array('ui-element', 'ui-password');
        if ($elementName) {
            $elementName                = 'name-' . str_replace('_', '-', strtolower($elementName));
            $elementClasses[]           = $elementName;
            $elementAttributes['id']    = $elementName;
        }
        $elementAttributes['class'] = implode(' ', $elementClasses);
        $this->setAttributes($elementAttributes);
    }

    protected function prepareLabelAttributes(array $elementAttributes = null)
    {
        // TODO: использовать обработку дополнительных классов !!!
        $elementAttributes = (array) $elementAttributes;
        $elementName       = $this->getName();
        $elementClasses    = array('ui-label');
        if ($elementName) {
            $elementName      = 'name-' . str_replace('_', '-', strtolower($elementName));
            $elementClasses[] = $elementName;
        }
        $elementAttributes['class'] = implode(' ', $elementClasses);
        $this->setLabelAttributes($elementAttributes);

    }

    public function __toString()
    {
        $passwordHelper = new PasswordHelper();
        $labelHelper    = new LabelHelper();
        $content  = '<div class="ui-element ui-password">';
        $content .= '<div class="ui-label">';
        $content .= $labelHelper->openTag($this);
        $content .= '<span>' . htmlspecialchars($this->getLabel()) . '</span>';
        $content .= $labelHelper->closeTag();
        $content .= '</div>';
        $content .= '<div class="ui-element">';
        $content .= $passwordHelper->render($this);
        $content .= '</div>';
        $content .= '</div>';
        return $content;
    }

}
